<template>
    <el-container>
        <el-aside>
            <div class="breadcrumb">
                <el-breadcrumb separator="/">
                    <el-breadcrumb-item :to="{ path: '/document' }">文档</el-breadcrumb-item>
                    <el-breadcrumb-item>
                        {{ name }}
                    </el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <div class="header">
                <span>目录</span>
                <Popover :visible="visible1" @toogleVisible="toogleVisible">
                    <el-button :icon="Plus" @click="visible1 = true" />
                    <template #popour>
                        <ul class="popour-list">
                            <li class="popour-list-item" @click="addDocument">新建文档</li>
                            <li class="popour-list-item" @click="() => {
                        visible1 = false;
                        dialogFormVisible = true;
                    }">新建分组</li>
                        </ul>
                    </template>
                </Popover>
            </div>
            <el-tree :data="dataSource" :props="defaultProps" node-key="id" default-expand-all
                :expand-on-click-node="false" @node-click="handleNodeClick" highlight-current check-on-click-node
                draggable @node-drop="handleDrop" current-node-key="27262146-40b3-49c2-ab2c-7a3ab927d5fa">
                <template #default="{ node, data }">
                    <span class="custom-tree-node">
                        <span class="label">{{ node.label }}</span>
                        <span v-if="selectedId === data.id">
                            <Popover :visible="visible2" @toogleVisible="toogleVisible2">
                                <el-button :icon="Plus" size="small" plain style="margin-right: 20px;"
                                    @click="visible2 = true" />
                                <template #popour>
                                    <ul class="popour-list">
                                        <li class="popour-list-item" @click="addDocumentHandle">新建文档</li>
                                        <li class="popour-list-item" @click="() => {
                        visible2 = false;
                        dialogFormVisible2 = true;
                        form2.parentChapter = selectedId;
                    }">新建分组</li>
                                    </ul>
                                </template>
                            </Popover>
                            <Popover :visible="visible3" @toogleVisible="toogleVisible3">
                                <el-button :icon="Setting" size="small" plain style="margin-right: 20px;"
                                    @click="visible3 = true" />
                                <template #popour>
                                    <ul class="popour-list">
                                        <li class="popour-list-item" @click="() => {
                        visible3 = false;
                        dialogFormVisible3 = true;
                        form3.title = node.label;
                    }">重命名</li>
                                        <li class="popour-list-item" @click="() => {
                        visible3 = false;
                        dialogVisible4 = true;
                    }">删除</li>
                                    </ul>
                                </template>
                            </Popover>
                        </span>
                    </span>
                </template>
            </el-tree>
        </el-aside>
        <el-main>
            <Edit v-if="isEdit" @changeIsEdit="changeIsEdit" :type="type" :parentChaptersId="parentChaptersId"
                :bookId="route.query.id as string" :id="selectedId" />
            <View v-else @changeIsEdit="changeIsEdit" :id="selectedId" />
        </el-main>
    </el-container>
    <el-dialog v-model="dialogFormVisible" title="新增分组" width="500">
        <el-form :model="form">
            <el-form-item label="标题">
                <el-input v-model="form.title" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="addChapterHandle">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog v-model="dialogFormVisible2" title="新增分组" width="500">
        <el-form :model="form2">
            <el-form-item label="父级">
                <el-input v-model="form2.parentChapter" disabled />
            </el-form-item>
            <el-form-item label="标题">
                <el-input v-model="form2.title" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible2 = false">取消</el-button>
                <el-button type="primary" @click="addChapterHandle2">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog v-model="dialogFormVisible3" title="重新命名" width="500">
        <el-form :model="form3">
            <el-form-item label="标题">
                <el-input v-model="form3.title" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible3 = false">取消</el-button>
                <el-button type="primary" @click="updateChapterHandle">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible4" title="删除" width="500">
        <span>请您确定是否删除?</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible4 = false">取消</el-button>
                <el-button type="primary" @click="deleteChapterHandle">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import Edit from '../components/Edit.vue'
import View from '../components/View.vue'
import Popover from '../components/Popover.vue'
import {
    Plus,
    Setting,
} from '@element-plus/icons-vue'
import { ref, reactive, onMounted } from 'vue'
import service from '../service/index'
import { useRoute } from 'vue-router';
import { to } from '../plugin/index'
import { ElLoading, ElMessage } from 'element-plus'
const { getChapters, addChapter, updatedChapter, changeDirectoryChapter } = service;
import type { IChaptersDataModal, IChaptersItemDataModal } from '../type';
import type Node from 'element-plus/es/components/tree/src/model/node'
import type {
    NodeDropType,
} from 'element-plus/es/components/tree/src/tree.type'

const route = useRoute();
const { name } = route.query;

interface Tree {
    id: string
    title: string
    children?: Tree[]
}

const dataSource = ref<Tree[]>([]);
const selectedId = ref<string>('');
const parentChaptersId = ref<string>('');
const type = ref<number>(1);

const dialogFormVisible = ref(false)
const dialogFormVisible2 = ref(false)
const dialogFormVisible3 = ref(false)
const dialogVisible4 = ref(false);

const visible1 = ref<boolean>(false);
const visible2 = ref<boolean>(false);
const visible3 = ref<boolean>(false);
const form = reactive({
    title: '',
})

const form2 = reactive({
    parentChapter: '',
    title: '',
})

const form3 = reactive({
    title: '',
})

const defaultProps = {
    children: 'children',
    label: 'title',
}

const toogleVisible = (flag: boolean) => {
    visible1.value = flag;
}
const toogleVisible2 = (flag: boolean) => {
    visible2.value = flag;
}

const toogleVisible3 = (flag: boolean) => {
    visible3.value = flag;
}

// 管理悬停状态
const hoveredNodeKey = ref(null);
const isEdit = ref(false);

const getChaptersHandle = async () => {
    const { id } = route.query;
    if (id) {
        const loading = ElLoading.service({
            lock: true,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0.7)',
        })
        const [res, err] = await to(getChapters({ bookId: id as string }));
        loading.close();
        const result = res.data;
        if (!err && result.code === 0) {
            // getChaptersHandle();
            dataSource.value = result.data;
        } else {
            ElMessage.error('新增数据失败');
            console.error(err);
        }
    }

}

const changeIsEdit = (val: boolean) => {
    isEdit.value = val;
    if (!val) {
        getChaptersHandle();
    }
}

const addChapterHandle = async () => {
    const { id } = route.query;
    if (id) {
        const params: IChaptersDataModal = {
            bookId: id as string,
            title: form.title,
            type: 2,
        }
        const loading = ElLoading.service({
            lock: true,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0.7)',
        })
        const [res, err] = await to(addChapter(params));
        loading.close();
        dialogFormVisible.value = false;
        ElMessage.success('新增成功');
        const result = res.data;
        if (!err && result.code === 0) {
            getChaptersHandle();
        } else {
            ElMessage.error('新增数据失败');
            console.error(err);
        }
    }
}

const addChapterHandle2 = async () => {
    const { id } = route.query;
    if (id) {
        const params: IChaptersDataModal = {
            bookId: id as string,
            title: form2.title,
            parentChaptersId: form2.parentChapter,
            type: 2,
        }
        const loading = ElLoading.service({
            lock: true,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0.7)',
        })
        const [res, err] = await to(addChapter(params));
        loading.close();
        dialogFormVisible2.value = false;
        ElMessage.success('新增成功');
        const result = res.data;
        if (!err && result.code === 0) {
            getChaptersHandle();
        } else {
            ElMessage.error('新增数据失败');
            console.error(err);
        }
    }
}

const updateChapterHandle = async () => {
    const params: IChaptersItemDataModal = {
        id: selectedId.value,
        title: form3.title,
    }
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    console.log(params);

    const [res, err] = await to(updatedChapter(params));
    loading.close();
    dialogFormVisible3.value = false;
    ElMessage.success('修改成功');
    const result = res.data;
    if (!err && result.code === 0) {
        getChaptersHandle();
    } else {
        ElMessage.error('修改数据失败');
        console.error(err);
    }
}

const deleteChapterHandle = async () => {
    const params: IChaptersItemDataModal = {
        id: selectedId.value,
        isDelete: 1,
    }
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    const [res, err] = await to(updatedChapter(params));
    loading.close();
    dialogVisible4.value = false;
    ElMessage.success('删除成功');
    const result = res.data;
    if (!err && result.code === 0) {
        getChaptersHandle();
    } else {
        ElMessage.error('删除数据失败');
        console.error(err);
    }
}

const addDocument = () => {
    parentChaptersId.value = null;
    isEdit.value = true;
    type.value = 1;
    visible1.value = false;
}

const addDocumentHandle = () => {
    parentChaptersId.value = selectedId.value;
    type.value = 3;
    isEdit.value = true;
}

const handleNodeClick = (data: Tree) => {
    selectedId.value = data.id;
    type.value = 2;
    isEdit.value = false;
}

const handleDrop = async (
    draggingNode: Node,
    dropNode: Node,
    dropType: NodeDropType,
) => {
    // console.log(draggingNode);
    // console.log(dropNode);
    // console.log(dropType);
    const { id } = draggingNode.data;
    const dropId = dropNode.data.id;
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })

    const [res, err] = await to(changeDirectoryChapter({ id, dropId, dropType }));
    loading.close();
    const result = res.data;
    if (!err && result.code === 0) {
        getChaptersHandle();
    } else {
        ElMessage.error('修改目录失败');
        console.error(err);
    }

}

onMounted(() => {
    getChaptersHandle();
})
</script>
<style lang="less" scoped>
.breadcrumb {
    padding-bottom: 30px;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px;
    margin-bottom: 20px;
    font-size: 15px;
}

.el-container {
    height: 100vh;
    padding: 20px;
}

.el-aside {
    width: 350px;
    border-right: 1px solid #eee;
}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}

.popour-list {
    list-style: none;
    padding: 0;
}

.popour-list-item {
    padding: 10px;
    cursor: pointer;
}

.popour-list-item:hover {
    background-color: #f5f7fa;
}

.label {
    width: 130px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

::v-deep(.el-tree-node__content) {
    padding: 20px 0;
}

::v-deep(.el-main) {
    padding: 0;
}
</style>